from django.shortcuts import render

# Create your views here.
from rest_framework import serializers, status, mixins
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from users import constants
from . import serializers

from users.models import User
from users.serializers import CreateUserSerializer, UserDetailSerializer


class UserView(CreateAPIView):

    # 先定义一个序列话器
    serializer_class = CreateUserSerializer





# TODO 检查用户名是否存在,查询用户名 如果查询的结果大于一 则为有重名
class UsernameCountView(APIView):
    def get(self,request,username):

        count = User.objects.filter(username = username).count()

        date ={
            'username' : username,
            'count': count
        }

        return Response(data=date)

# TODO 检查手机号 是否存在
class MobileCountView(APIView):
    def get(self,request,mobile):
        count = User.objects.filter(mobile = mobile).count()


        data = {
            'mobile':mobile,
            'count':count
        }
        return Response(data)

# GET /user/
# TODO 用户基本信息查询
class UserDetailView(RetrieveAPIView):
    # TODO 这块可能出错，，，，
    serializer_class = serializers.UserDetailSerializer
    # 指明用户只有登录才可以访问个人中心
    permission_classes = [IsAuthenticated]
    # queryset = User.objects.all()
    def get_object(self):

        # 获取user对象
        return self.request.user


# TODO 邮件验证的逻辑
class EmailView(UpdateAPIView):
    serializer_class = serializers.EmailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user


# TODO 邮箱验证
class VerifyEmailView(APIView):

    def get(self,request):
        # 从相应的数据中取到 token的值
        token = request.query_params.get('token')
        if not token:
            return Response({'message':'缺少token'},status = status.HTTP_400_BAD_REQUEST)

        # 校验token
        user = User.check_verity_email_token(token)
        if user is None:
            return Response({'message':'链接信息无效'},status = status.HTTP_400_BAD_REQUEST)

        else:
            user.email_active = True
            user.save()
            return Response({'message':'OK'})



# TODO 用户地址新增与修改
class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    serializer_class = serializers.UserAddressSerializer
    permissions = [IsAuthenticated]


    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self,request,*args,**kwargs):
        """用户地址列表数据"""
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset,many=True)
        user = self.request.user
        return Response({
            'user_id':user.id,
            'default_address_id' :user.default_address_id,
            'limit':constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)













